// src-tauri/src/weighted_approval.rs
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use lru::LruCache;

use crate::{
    trust_tree::{TrustTree, TrustCertificate},
    crypto::{CryptoService, CryptoError},
};

#[derive(Serialize, Deserialize, Clone)]
pub struct WeightedApproval {
    pub content_hash: String,
    pub approver_peer_id: String,
    pub approver_trust_level: u8,
    pub approval_weight: f64,
    pub approval_date: u64,
    pub comments: String,
    pub signature: String, // 数字签名
}

#[derive(Serialize, Deserialize, Clone)]
pub struct SignedApproval {
    pub approval_data: ApprovalData,
    pub signature: String,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct ApprovalData {
    pub content_hash: String,
    pub approver_peer_id: String,
    pub approver_trust_level: u8,
    pub approval_weight: f64,
    pub approval_date: u64,
    pub comments: String,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct VerifiedApproval {
    pub approval_data: ApprovalData,
    pub signature: String,
    pub is_signature_valid: bool,
    pub approver_public_key: String,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct ContentApprovalResult {
    pub content_hash: String,
    pub submitter_peer_id: String,
    pub approved: bool,
    pub approval_weight: f64,
    pub required_approvals: usize,
    pub current_approvals: usize,
}

pub struct WeightedApprovalSystem {
    trust_tree: TrustTree,
    approval_threshold: f64,
    content_approvals: HashMap<String, Vec<WeightedApproval>>, // content_hash -> approvals
    approval_cache: LruCache<String, ApprovalStatus>, // content_hash -> 批准状态缓存
    required_trust_level: u8, // 最低信任级别要求
}

struct ApprovalStatus {
    content_hash: String,
    is_approved: bool,
    total_weight: f64,
    approval_count: usize,
    validation_timestamp: u64,
}

impl WeightedApprovalSystem {
    pub fn new(trust_tree: TrustTree, approval_threshold: f64, required_trust_level: u8) -> Self {
        Self {
            trust_tree,
            approval_threshold,
            content_approvals: HashMap::new(),
            approval_cache: LruCache::new(500),
            required_trust_level,
        }
    }

    /// 提交带签名的内容批准
    pub fn submit_signed_approval(
        &mut self,
        crypto_service: &CryptoService,
        content_hash: String,
        approver_peer_id: String,
        comments: String,
    ) -> Result<SignedApproval, CryptoError> {
        // 获取批准者证书和信任级别
        let approver_cert = self.trust_tree.get_certificate(&approver_peer_id)
            .ok_or(CryptoError("Approver not authorized".to_string()))?;

        // 检查批准者信任级别是否足够
        if approver_cert.trust_level < self.required_trust_level {
            return Err(CryptoError("Approver trust level too low".to_string()));
        }

        // 计算批准权重
        let approval_weight = self.calculate_approval_weight(approver_cert.trust_level);

        // 创建批准数据
        let approval_data = ApprovalData {
            content_hash: content_hash.clone(),
            approver_peer_id: approver_peer_id.clone(),
            approver_trust_level: approver_cert.trust_level,
            approval_weight,
            approval_date: current_timestamp(),
            comments: comments.clone(),
        };

        // 序列化批准数据用于签名
        let approval_bytes = serde_json::to_vec(&approval_data)
            .map_err(|e| CryptoError(format!("Failed to serialize approval: {}", e)))?;

        // 生成数字签名
        let signature = crypto_service.sign_data(&approver_peer_id, &approval_bytes)?;

        let signed_approval = SignedApproval {
            approval_data,
            signature: signature.clone(),
        };

        // 验证签名（确保正确性）
        let is_valid = crypto_service.verify_signature(
            &approver_cert.public_key,
            &approval_bytes,
            &signature
        )?;

        if !is_valid {
            return Err(CryptoError("Approval signature verification failed".to_string()));
        }

        // 创建WeightedApproval记录
        let weighted_approval = WeightedApproval {
            content_hash: content_hash.clone(),
            approver_peer_id: approver_peer_id.clone(),
            approver_trust_level: approver_cert.trust_level,
            approval_weight,
            approval_date: current_timestamp(),
            comments,
            signature,
        };

        // 添加到批准记录
        self.content_approvals
            .entry(content_hash.clone())
            .or_insert_with(Vec::new)
            .push(weighted_approval);

        // 清理缓存，因为批准状态已改变
        self.approval_cache.pop(&content_hash);

        Ok(signed_approval)
    }

    /// 基于信任级别计算批准权重
    fn calculate_approval_weight(&self, trust_level: u8) -> f64 {
        // 信任级别越高，权重越高
        match trust_level {
            0 => 10.0, // God Peer
            1 => 5.0,  // 一级Trusted Peer
            2 => 2.0,  // 二级
            3 => 1.0,  // 三级
            4 => 0.5,  // 四级
            5 => 0.25, // 五级
            6 => 0.1,  // 六级
            _ => 0.05, // 七级及以下
        }
    }

    /// 检查内容是否已获批准
    pub fn is_content_approved(&mut self, content_hash: &str) -> bool {
        // 检查缓存
        if let Some(status) = self.approval_cache.get(content_hash) {
            return status.is_approved;
        }

        // 计算总批准权重
        let total_weight = self.calculate_total_approval_weight(content_hash);
        let approval_count = self.get_approval_count(content_hash);
        let is_approved = total_weight >= self.approval_threshold;

        // 缓存结果
        let status = ApprovalStatus {
            content_hash: content_hash.to_string(),
            is_approved,
            total_weight,
            approval_count,
            validation_timestamp: current_timestamp(),
        };
        self.approval_cache.put(content_hash.to_string(), status);

        is_approved
    }

    /// 计算指定内容的总批准权重
    fn calculate_total_approval_weight(&self, content_hash: &str) -> f64 {
        self.content_approvals
            .get(content_hash)
            .map(|approvals| {
                approvals.iter()
                    .map(|approval| approval.approval_weight)
                    .sum()
            })
            .unwrap_or(0.0)
    }

    /// 获取指定内容的批准数量
    fn get_approval_count(&self, content_hash: &str) -> usize {
        self.content_approvals
            .get(content_hash)
            .map(|approvals| approvals.len())
            .unwrap_or(0)
    }

    /// 获取内容的批准状态详情
    pub fn get_approval_status(&mut self, content_hash: &str) -> ContentApprovalResult {
        let total_weight = self.calculate_total_approval_weight(content_hash);
        let approval_count = self.get_approval_count(content_hash);
        let is_approved = total_weight >= self.approval_threshold;

        ContentApprovalResult {
            content_hash: content_hash.to_string(),
            submitter_peer_id: "".to_string(), // 需要从其他地方获取
            approved: is_approved,
            approval_weight: total_weight,
            required_approvals: self.calculate_required_approvals(total_weight),
            current_approvals: approval_count,
        }
    }

    /// 计算还需要多少批准
    fn calculate_required_approvals(&self, current_weight: f64) -> usize {
        if current_weight >= self.approval_threshold {
            return 0;
        }

        let remaining_weight = self.approval_threshold - current_weight;
        
        // 假设需要最低级别Trusted Peer的批准
        let min_approval_weight = self.calculate_approval_weight(self.required_trust_level);
        (remaining_weight / min_approval_weight).ceil() as usize
    }

    /// 获取已验证的批准列表
    pub fn get_verified_approvals(
        &self,
        crypto_service: &CryptoService,
        content_hash: &str,
    ) -> Result<Vec<VerifiedApproval>, CryptoError> {
        let approvals = self.content_approvals.get(content_hash)
            .map(|v| v.as_slice())
            .unwrap_or(&[]);

        let mut verified_approvals = Vec::new();

        for approval in approvals {
            // 获取批准者证书
            let approver_cert = self.trust_tree.get_certificate(&approval.approver_peer_id)
                .ok_or(CryptoError("Approver certificate not found".to_string()))?;

            // 创建批准数据用于验证
            let approval_data = ApprovalData {
                content_hash: approval.content_hash.clone(),
                approver_peer_id: approval.approver_peer_id.clone(),
                approver_trust_level: approval.approver_trust_level,
                approval_weight: approval.approval_weight,
                approval_date: approval.approval_date,
                comments: approval.comments.clone(),
            };

            // 序列化用于验证
            let approval_bytes = serde_json::to_vec(&approval_data)
                .map_err(|e| CryptoError(format!("Failed to serialize approval: {}", e)))?;

            // 验证签名
            let is_signature_valid = crypto_service.verify_signature(
                &approver_cert.public_key,
                &approval_bytes,
                &approval.signature
            )?;

            verified_approvals.push(VerifiedApproval {
                approval_data,
                signature: approval.signature.clone(),
                is_signature_valid,
                approver_public_key: approver_cert.public_key.clone(),
            });
        }

        Ok(verified_approvals)
    }

    /// 获取需要批准的内容列表
    pub fn get_pending_approvals(&self) -> Vec<String> {
        let mut pending = Vec::new();

        for (content_hash, approvals) in &self.content_approvals {
            let total_weight: f64 = approvals.iter()
                .map(|a| a.approval_weight)
                .sum();

            if total_weight < self.approval_threshold {
                pending.push(content_hash.clone());
            }
        }

        pending
    }

    /// 获取已批准的内容列表
    pub fn get_approved_content(&self) -> Vec<String> {
        let mut approved = Vec::new();

        for (content_hash, approvals) in &self.content_approvals {
            let total_weight: f64 = approvals.iter()
                .map(|a| a.approval_weight)
                .sum();

            if total_weight >= self.approval_threshold {
                approved.push(content_hash.clone());
            }
        }

        approved
    }

    /// 撤销批准
    pub fn revoke_approval(
        &mut self,
        content_hash: &str,
        approver_peer_id: &str,
    ) -> Result<(), CryptoError> {
        if let Some(approvals) = self.content_approvals.get_mut(content_hash) {
            approvals.retain(|approval| approval.approver_peer_id != approver_peer_id);
            
            // 清理缓存
            self.approval_cache.pop(content_hash);
            
            Ok(())
        } else {
            Err(CryptoError("Content hash not found".to_string()))
        }
    }

    /// 清理过期缓存
    pub fn cleanup_cache(&mut self) {
        let current_time = current_timestamp();
        let expired_keys: Vec<String> = self.approval_cache.iter()
            .filter(|(_, status)| current_time - status.validation_timestamp > 3600) // 1小时过期
            .map(|(key, _)| key.clone())
            .collect();

        for key in expired_keys {
            self.approval_cache.pop(&key);
        }
    }

    /// 获取系统统计信息
    pub fn get_statistics(&self) -> ApprovalStatistics {
        let total_content = self.content_approvals.len();
        let approved_content = self.get_approved_content().len();
        let pending_content = self.get_pending_approvals().len();

        ApprovalStatistics {
            total_content,
            approved_content,
            pending_content,
            approval_threshold: self.approval_threshold,
            required_trust_level: self.required_trust_level,
        }
    }
}

#[derive(Serialize, Deserialize, Clone)]
pub struct ApprovalStatistics {
    pub total_content: usize,
    pub approved_content: usize,
    pub pending_content: usize,
    pub approval_threshold: f64,
    pub required_trust_level: u8,
}

fn current_timestamp() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()
}